package com.ybb.vue.common.security;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ybb.vue.common.R;
import com.ybb.vue.entity.SysMenu;
import com.ybb.vue.entity.SysRole;
import com.ybb.vue.entity.SysUser;
import com.ybb.vue.service.Impl.SysMenuServiceImpl;
import com.ybb.vue.service.Impl.SysRoleServiceImpl;
import com.ybb.vue.service.Impl.SysUserServieceImpl;
import com.ybb.vue.common.util.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * 自定义处理器-登陆成功
 */
@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    private SysUserServieceImpl sysUserServiece;

    @Autowired
    private SysRoleServiceImpl sysRoleService;

    @Autowired
    private SysMenuServiceImpl sysMenuService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        response.setContentType("application/json;charset=UTF-8");
        ServletOutputStream outputStream = response.getOutputStream();

        String username = authentication.getName();
        String token = JwtUtils.genJwtToken(username);

        SysUser user = sysUserServiece.getByUsername(username);
        // 更新用户最后登陆时间
        user.setLastLoginTime(new Date());

        List<SysRole> roleList = sysRoleService.list(new QueryWrapper<SysRole>().inSql("id", "select role_id from sys_user_role where user_id=" + user.getId()));
        // 遍历所有角色，获取所有菜单权限，而且不重复
        Set<SysMenu> menuSet = new HashSet<>();
        for (SysRole sysRole : roleList) {
            List<SysMenu> sysMenuList = sysMenuService.list(new QueryWrapper<SysMenu>().inSql("id", "select menu_id from sys_role_menu where role_id=" + sysRole.getId()));
            for (SysMenu sysMenu : sysMenuList) {
                menuSet.add(sysMenu);
            }
        }

        // set转为list
        List<SysMenu> sysMenuList = new ArrayList<>(menuSet);

        // 排序
        sysMenuList.sort(Comparator.comparing(SysMenu::getOrderNum));

        // 生成菜单树
        List<SysMenu> menuTree = sysMenuService.buildTreeMenu(sysMenuList);

        sysUserServiece.updateById(user);
        outputStream.write(JSONUtil.toJsonStr(R.ok().put("authorization",token).put("user",user).put("menuTree",menuTree)).getBytes());
        outputStream.flush();
        outputStream.close();
    }

}
